package com.ycl.bookstore.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.bookstore.common.Result;
import com.ycl.bookstore.mapper.BooksMapper;
import com.ycl.bookstore.pojo.Books;
import com.ycl.bookstore.pojo.ShoppingCart;
import com.ycl.bookstore.service.ShoppingCartService;
import com.ycl.bookstore.mapper.ShoppingCartMapper;
import com.ycl.bookstore.utils.MyThreadLocal;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ycl.bookstore.utils.RedisConstants.BOOK_LIST_KEY;
import static com.ycl.bookstore.utils.RedisConstants.SHOP_CART_KEY;

/**
 *
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private BooksMapper booksMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询购物车列表
     *
     * @return
     */
    @Override
    public Result getShopList(String title, Long pageNo, Long pageSize) {
        //模糊查询
        if (title != null) {
            return Result.success();
        }
        //获取用户id
        Long userId = MyThreadLocal.getUser().getId();
        Set<Object> keys = stringRedisTemplate.opsForHash().keys(SHOP_CART_KEY + userId);
        if(keys==null){
            return Result.fail("购物车出事故了");
        }
        if(keys.size()==0){
            return Result.success(new LinkedList<>());
        }
        List<ShoppingCart> shopCartList = new LinkedList<>();
        for (Object key : keys) {
            String jsonStr = (String) stringRedisTemplate.opsForHash().get(SHOP_CART_KEY + userId, key);
            //将json对象转化为json对象
            ShoppingCart shoppingCart = JSONUtil.toBean(jsonStr, ShoppingCart.class);
            shopCartList.add(shoppingCart);
        }
        return Result.success(shopCartList);
    }

    /**
     * 加入购物车
     *
     * @param bookId
     * @return
     */
    @Override
    public Result addShopCart(String bookId) {
        Long userId = MyThreadLocal.getUser().getId();
        String cartKey = SHOP_CART_KEY + userId;
        //判断购物车是否存在该书籍
        Object book = stringRedisTemplate.opsForHash().get(cartKey, bookId);
        //redis存在数据 表示存在购物车中
        if (book != null) {
            return Result.success("购物车已存在该商品");
        }
        //购物车中不存在
        String cart = getCart(bookId);
        stringRedisTemplate.opsForHash().put(cartKey, bookId, cart);
        return Result.success();
    }

    /**
     * 取消购物车
     *
     * @param bookId
     * @return
     */
    @Override
    public Result cancelShopCart(Long bookId) {
        //获取用户id
        Long userId = MyThreadLocal.getUser().getId();
        Long count = stringRedisTemplate.opsForHash().delete(SHOP_CART_KEY + userId, bookId + "");
        if (count <= 0) {
            return Result.fail("取消失败");
        }
        return Result.success();
    }

    /**
     * 清除购物车
     * @return
     */
    @Override
    public Result clearShopCart() {
        //获取用户id
        Long userId = MyThreadLocal.getUser().getId();
        // 判断购物车是否是空的
        if(stringRedisTemplate.opsForHash().size(SHOP_CART_KEY+userId)<1){
            return Result.success("购物车空空如也,快来加入购物车吧");
        }
        //删除key
        stringRedisTemplate.delete(SHOP_CART_KEY+userId);
        return Result.success("清除成功");
    }

    /**
     * 得到购物车json对象
     *
     * @return
     */
    public String getCart(String bookId) {
        //Books books = booksMapper.selectById(bookId);
        //从redis中取出数据(因为之前展示数据库的时候  已经将书籍存入了redis中  当加入购物车中  直接从redis中获取书籍信息  减少了对数据库的压力)
        Double id = Double.valueOf(bookId);
        Set<String> set = stringRedisTemplate.opsForZSet().rangeByScore(BOOK_LIST_KEY, id, id);
        Books books = null;
        for (String s : set) {
            books = JSONUtil.toBean(s, Books.class);
        }
        //获取当前时间
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //创建购物车对象
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setBookId(books.getId());
        shoppingCart.setTitle(books.getTitle());
        shoppingCart.setAuthor(books.getAuthor());
        shoppingCart.setPrice(books.getPrice());
        shoppingCart.setCreatedAt(createTime);
        String jsonStr = JSONUtil.toJsonStr(shoppingCart);
        return jsonStr;
    }
}




